package first_practice;

/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-41-缺失的第一个正数
 * @date 2025/3/27 14:23
 */
public class Solution41 {

    public static void main(String[] args) {
        int[] nums = {4,3,4,1,1,4,1,4};
        System.out.println(firstMissingPositive(nums));

    }

    public static int firstMissingPositive(int[] nums) {
        // 将数组视为Hash表
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            // 使用while循环免得遗漏元素
            while (nums[i] > 0 && nums[i] < len && nums[i] != i + 1) {
                int temp = nums[i];
                swap(nums, i);
                if (nums[i] == temp) break; // 跳出重复循环
            }
        }
        for (int i = 0; i < len; i++) {
            if (nums[i] != i + 1)
                return i + 1;
        }
        return len + 1;
    }

    private static void swap(int[] nums, int i) {
        // 将num放在索引为num-1的位置
        int temp = nums[nums[i] - 1];
        nums[nums[i] - 1] = nums[i];
        nums[i] = temp;
    }
}
